package com.kanche.bigbaby.collection;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import com.kanche.bigbaby.R;
import com.kanche.bigbaby.collection.domain.VehicleModel;
import com.kanche.bigbaby.support.awesome.DrawableAwesome;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

//import com.kkche.merchant.R;
//import com.kkche.merchant.adpaters.VehicleSelectorAdapter;
//import com.kkche.merchant.awesome.DrawableAwesome;
//import com.kkche.merchant.awesome.LetterView;
//import com.kkche.merchant.data.VehicleModelsDBHelper;
//import com.kkche.merchant.domain.VehicleModel;

/**
 * Created by nealmi on 6/12/14.
 */
public class VehicleModelSelectorFragment extends Fragment implements AdapterView.OnItemClickListener {
    public static final int VEHICLE_TYPE_BRAND = 0;
    private int type = VEHICLE_TYPE_BRAND;
    public static final int VEHICLE_TYPE_SERIES = 1;
    public static final int VEHICLE_TYPE_MODEL = 2;
    private static final String TAG = "Merchant:VehicleModelSelectorFragment";
    private View container;
    private VehicleModelsDBHelper dbHelper;
    private VehicleSelectorAdapter vehicleSelectorAdapter;
    private StickyListHeadersListView listView;
    private ItemSelectedListener itemSelectedListener;
    private VehicleModel queryModel;
    private boolean allowUnlimited;
    private LetterView layoutIndex;
    private TextView tv_show;
    private String[] letters;

    public VehicleModelSelectorFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vehicleSelectorAdapter = new VehicleSelectorAdapter(queryData(), type, getActivity());
        allowUnlimited = getArguments().getBoolean("allowUnlimited", false);
    }


//    public VehicleModelSelectorFragment(int type, VehicleModel queryModel) {
//        this.type = type;
//        this.queryModel = queryModel;
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
        super.onCreateView(inflater, root, savedInstanceState);
        container = inflater.inflate(R.layout.fragment_vehicle_selector, root, false);
        ImageButton button = (ImageButton) container.findViewById(R.id.closeButton);
        button.setVisibility(View.GONE);
        layoutIndex = (LetterView) container.findViewById(R.id.vehicle_selector_layout);
        if(type == VEHICLE_TYPE_BRAND){
            layoutIndex.setVisibility(View.VISIBLE);
            letters = (String[]) vehicleSelectorAdapter.getSections();
            layoutIndex.setStringArray(letters);
        }
        layoutIndex.setOnTouchLetterChangeListenner(new LetterView.OnTouchLetterChangeListenner() {
            @Override
            public void onTouchLetterChange(boolean isTouched, String s) {
                tv_show.setText(s);
                if (isTouched) {
                    tv_show.setVisibility(View.VISIBLE);
                } else {
                    tv_show.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            tv_show.setVisibility(View.GONE);
                        }
                    }, 100);
                }
                if (!s.equals("Z")) {
                    listView.setSelection(vehicleSelectorAdapter.getPositionForSection(Arrays.binarySearch(letters, s)));
                }
            }

        });
        tv_show = (TextView) container.findViewById(R.id.tv);
        tv_show.setVisibility(View.GONE);
        if (type == VEHICLE_TYPE_SERIES) {
            button.setVisibility(View.VISIBLE);
            container.setLayoutParams(
                    new FrameLayout.LayoutParams(Math.round(root.getWidth() * .75f), root.getHeight(), Gravity.RIGHT));
//            layoutIndex.setVisibility(View.GONE);
        }
        if (type == VEHICLE_TYPE_MODEL) {
            button.setVisibility(View.VISIBLE);
            container.setLayoutParams(
                    new FrameLayout.LayoutParams(Math.round(root.getWidth() * .45f), root.getHeight(), Gravity.RIGHT));
//            layoutIndex.setVisibility(View.GONE);
        }

        listView = (StickyListHeadersListView) container.findViewById(R.id.stickyHeaderListView);


        listView.setAdapter(vehicleSelectorAdapter);
        listView.setOnItemClickListener(this);
        queryDataAsync();

        Drawable drawable = new DrawableAwesome.DrawableAwesomeBuilder(getActivity(), R.string.fa_angle_double_right)
                .setColor(getResources().getColor(R.color.black_translucent))
                .build();
        button.setImageDrawable(drawable);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hide();
            }
        });

        return container;
    }

    public void hide() {
        getFragmentManager().beginTransaction()
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
                .hide(this)
                .commit();
    }

    public void show() {
        getFragmentManager().beginTransaction()
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .show(this)
                .commit();
    }

    private void queryDataAsync() {
        final ProgressDialog
                progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.show();

        new AsyncTask<Void, Void, List<VehicleModel>>() {
            @Override
            protected List<VehicleModel> doInBackground(Void... params) {
                return queryData();
            }

            @Override
            protected void onPostExecute(List<VehicleModel> vehicleModels) {
                super.onPostExecute(vehicleModels);
                vehicleSelectorAdapter = new VehicleSelectorAdapter(vehicleModels, type, getActivity());

                listView.setAdapter(vehicleSelectorAdapter);
                if (progressDialog != null)
                    progressDialog.dismiss();
            }
        }.execute();
    }

    private List<VehicleModel> queryData() {
        if (dbHelper == null)
            dbHelper = new VehicleModelsDBHelper(getActivity());

        List<VehicleModel> models = new ArrayList<VehicleModel>();
        switch (type) {
            case VEHICLE_TYPE_BRAND:
                models = dbHelper.queryBrands();
                models.addAll(0, VehicleModel.getHotBrands());
                break;
            case VEHICLE_TYPE_SERIES:
                models = dbHelper.querySeries(queryModel);
                break;
            case VEHICLE_TYPE_MODEL:
                models = dbHelper.queryModels(queryModel);
                break;
        }
        if (allowUnlimited) {
            VehicleModel unlimited = new VehicleModel();
            unlimited.setId(VehicleModel.UNLIMITED_ID);
            if (queryModel != null && StringUtils.hasText(queryModel.getBrand())) {
                unlimited.setBrand(queryModel.getBrand());
            } else {
                unlimited.setBrand("不限");

            }
            if (queryModel != null && StringUtils.hasText(queryModel.getSeries())) {
                unlimited.setSeries(queryModel.getSeries());
            } else {
                unlimited.setSeries("不限");
            }
            if (queryModel != null && StringUtils.hasText(queryModel.getSaleName())) {
                unlimited.setSaleName(queryModel.getSaleName());
            } else {
                unlimited.setSaleName("不限");
            }
            models.add(0, unlimited);
        }
        return models;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (itemSelectedListener != null) {
            VehicleModel result;
            VehicleModel v = (VehicleModel) adapterView.getItemAtPosition(i);
            if (type == VEHICLE_TYPE_MODEL && v.getId() != VehicleModel.UNLIMITED_ID) {
                result = dbHelper.queryVehicleModel(v);
            } else {
                result = v;
            }
            if (allowUnlimited && result.getId() == VehicleModel.UNLIMITED_ID && queryModel != null) {
                result.setBrand(queryModel.getBrand());
                result.setSeries(queryModel.getSeries());
                result.setSaleName(queryModel.getSaleName());
            }
            itemSelectedListener.onItemClick(type, result);
        }
    }

    public ItemSelectedListener getItemSelectedListener() {
        return itemSelectedListener;
    }

    public void setItemSelectedListener(ItemSelectedListener itemSelectedListener) {
        this.itemSelectedListener = itemSelectedListener;
    }

    public void updateDataWithCondition(VehicleModel queryModel) {
        this.queryModel = queryModel;
        if (isAdded()) {
            queryDataAsync();
        }
//        vehicleSelectorAdapter.refresh(queryData());
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }


    public VehicleModel getQueryModel() {
        return queryModel;
    }

    public void setQueryModel(VehicleModel queryModel) {
        this.queryModel = queryModel;
//        vehicleSelectorAdapter.refresh(queryData());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }

    public interface ItemSelectedListener {
        public void onItemClick(int type, VehicleModel model);
    }
}
